<template>
  <div class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <div class="flex justify-between items-center">
          <div class="text-center md:text-left">
            <div class="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-emerald-600 to-teal-600 rounded-2xl mb-4 shadow-lg">
              <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
              </svg>
            </div>
            <h1 class="text-4xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent mb-2">创建题目</h1>
            <p class="text-gray-600 text-lg">创建新的编程题目</p>
          </div>
          <button
            class="px-6 py-3 bg-gradient-to-r from-gray-500 to-gray-600 text-white rounded-xl hover:from-gray-600 hover:to-gray-700 transition-all duration-200 transform hover:scale-105 shadow-lg hover:shadow-xl"
            @click="goBack"
          >
            <svg class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
            </svg>
            返回
          </button>
        </div>
      </div>

      <!-- 创建题目表单 -->
      <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-8 border border-white/20">
        <form @submit.prevent="handleSubmit" class="space-y-8">
          <!-- 基本信息 -->
          <div class="bg-gradient-to-r from-blue-50 to-indigo-50 p-6 rounded-2xl border border-blue-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              </svg>
              基本信息
            </h3>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <!-- 题目标题 -->
              <div class="lg:col-span-2">
                <label for="title" class="block text-sm font-medium text-gray-700 mb-3">
                  题目标题 <span class="text-red-500">*</span>
                </label>
                <input
                  id="title"
                  v-model="form.title"
                  type="text"
                  required
                  maxlength="200"
                  class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-blue-500/30 focus:border-blue-500 transition-all duration-200 shadow-sm hover:shadow-md"
                  placeholder="请输入题目标题"
                />
                <p class="text-sm text-gray-500 mt-2">{{ form.title.length }}/200</p>
              </div>

              <!-- 难度 -->
              <div>
                <label for="difficulty" class="block text-sm font-medium text-gray-700 mb-3">
                  难度 <span class="text-red-500">*</span>
                </label>
                <select
                  id="difficulty"
                  v-model="form.difficulty"
                  required
                  class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-blue-500/30 focus:border-blue-500 transition-all duration-200 shadow-sm hover:shadow-md"
                >
                  <option value="">请选择难度</option>
                  <option value="Easy">简单</option>
                  <option value="Medium">中等</option>
                  <option value="Hard">困难</option>
                </select>
              </div>

              <!-- 来源 -->
              <div>
                <label for="source" class="block text-sm font-medium text-gray-700 mb-3">
                  题目来源
                </label>
                <input
                  id="source"
                  v-model="form.source"
                  type="text"
                  class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-blue-500/30 focus:border-blue-500 transition-all duration-200 shadow-sm hover:shadow-md"
                  placeholder="如：LeetCode、牛客网等"
                />
              </div>

              <!-- 时间限制 -->
              <div>
                <label for="timeLimit" class="block text-sm font-medium text-gray-700 mb-3">
                  时间限制 (毫秒)
                </label>
                <input
                  id="timeLimit"
                  v-model.number="form.timeLimit"
                  type="number"
                  min="100"
                  max="10000"
                  class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-blue-500/30 focus:border-blue-500 transition-all duration-200 shadow-sm hover:shadow-md"
                  placeholder="默认1000ms"
                />
              </div>

              <!-- 内存限制 -->
              <div>
                <label for="memoryLimit" class="block text-sm font-medium text-gray-700 mb-3">
                  内存限制 (MB)
                </label>
                <input
                  id="memoryLimit"
                  v-model.number="form.memoryLimit"
                  type="number"
                  min="64"
                  max="1024"
                  class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-blue-500/30 focus:border-blue-500 transition-all duration-200 shadow-sm hover:shadow-md"
                  placeholder="默认256MB"
                />
              </div>
            </div>
          </div>

          <!-- 题目内容 -->
          <div class="bg-gradient-to-r from-emerald-50 to-teal-50 p-6 rounded-2xl border border-emerald-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
              </svg>
              题目内容
            </h3>
            <div>
              <label for="content" class="block text-sm font-medium text-gray-700 mb-3">
                题目描述 <span class="text-red-500">*</span>
              </label>
              <textarea
                id="content"
                v-model="form.content"
                required
                rows="8"
                class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 transition-all duration-200 shadow-sm hover:shadow-md"
                placeholder="请详细描述题目要求..."
              ></textarea>
            </div>
          </div>

          <!-- 输入输出格式 -->
          <div class="bg-gradient-to-r from-amber-50 to-orange-50 p-6 rounded-2xl border border-amber-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
              </svg>
              输入输出格式
            </h3>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <div>
                <label for="inputFormat" class="block text-sm font-medium text-gray-700 mb-3">
                  输入格式
                </label>
                <textarea
                  id="inputFormat"
                  v-model="form.inputFormat"
                  rows="4"
                  class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-amber-500/30 focus:border-amber-500 transition-all duration-200 shadow-sm hover:shadow-md"
                  placeholder="描述输入数据的格式..."
                ></textarea>
              </div>

              <div>
                <label for="outputFormat" class="block text-sm font-medium text-gray-700 mb-3">
                  输出格式
                </label>
                <textarea
                  id="outputFormat"
                  v-model="form.outputFormat"
                  rows="4"
                  class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-amber-500/30 focus:border-amber-500 transition-all duration-200 shadow-sm hover:shadow-md"
                  placeholder="描述输出数据的格式..."
                ></textarea>
              </div>
            </div>
          </div>

          <!-- 约束条件 -->
          <div class="bg-gradient-to-r from-purple-50 to-pink-50 p-6 rounded-2xl border border-purple-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
              </svg>
              约束条件
            </h3>
            <div>
              <label for="constraints" class="block text-sm font-medium text-gray-700 mb-3">
                约束条件
              </label>
              <textarea
                id="constraints"
                v-model="form.constraints"
                rows="3"
                class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-purple-500/30 focus:border-purple-500 transition-all duration-200 shadow-sm hover:shadow-md"
                placeholder="描述题目的约束条件..."
              ></textarea>
            </div>
          </div>

          <!-- 样例输入输出 -->
          <div class="bg-gradient-to-r from-cyan-50 to-blue-50 p-6 rounded-2xl border border-cyan-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-cyan-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
              </svg>
              样例输入输出
            </h3>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <div>
                <label for="sampleInput" class="block text-sm font-medium text-gray-700 mb-3">
                  样例输入
                </label>
                <textarea
                  id="sampleInput"
                  v-model="form.sampleInput"
                  rows="4"
                  class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-cyan-500/30 focus:border-cyan-500 transition-all duration-200 shadow-sm hover:shadow-md font-mono text-sm"
                  placeholder="输入样例数据..."
                ></textarea>
              </div>

              <div>
                <label for="sampleOutput" class="block text-sm font-medium text-gray-700 mb-3">
                  样例输出
                </label>
                <textarea
                  id="sampleOutput"
                  v-model="form.sampleOutput"
                  rows="4"
                  class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-cyan-500/30 focus:border-cyan-500 transition-all duration-200 shadow-sm hover:shadow-md font-mono text-sm"
                  placeholder="输出样例数据..."
                ></textarea>
              </div>
            </div>
          </div>

          <!-- 代码模板 -->
          <div class="bg-gradient-to-r from-indigo-50 to-purple-50 p-6 rounded-2xl border border-indigo-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"></path>
              </svg>
              代码模板
            </h3>
            <p class="text-sm text-gray-600 mb-6">为不同编程语言提供代码模板，请在主程序给代码模版用<code class="text-red-700 px-1 py-0.5 rounded-md">// CODE_PLACEHOLDER</code>作为占位符</p>
            
            <!-- 语言选择 -->
            <div class="mb-6">
              <div class="flex flex-wrap gap-3">
                <button
                  v-for="lang in programmingLanguages"
                  :key="lang.value"
                  type="button"
                  :class="[
                    'px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 shadow-sm hover:shadow-md',
                    selectedLanguage === lang.value
                      ? 'bg-gradient-to-r from-indigo-500 to-indigo-600 text-white shadow-md'
                      : 'bg-white/80 backdrop-blur-sm border border-gray-200/50 text-gray-700 hover:bg-gray-50'
                  ]"
                  @click="selectLanguage(lang.value as ProgrammingLanguage)"
                >
                  {{ lang.label }}
                </button>
              </div>
            </div>

            <!-- 代码编辑器 -->
            <div v-if="selectedLanguage" class="space-y-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-3">
                  {{ programmingLanguages.find(l => l.value === selectedLanguage)?.label }} 代码模板
                </label>
                <textarea
                  v-model="basecodeTemplates[selectedLanguage]"
                  rows="12"
                  class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-500 transition-all duration-200 shadow-sm hover:shadow-md font-mono text-sm"
                  :placeholder="`请输入${programmingLanguages.find(l => l.value === selectedLanguage)?.label}代码模板...`"
                ></textarea>
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-3">
                  {{ programmingLanguages.find(l => l.value === selectedLanguage)?.label }} 主程序代码
                </label>
                <textarea
                  v-model="runCodeTemplates[selectedLanguage]"
                  rows="8"
                  class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-500 transition-all duration-200 shadow-sm hover:shadow-md font-mono text-sm"
                  :placeholder="`请输入${programmingLanguages.find(l => l.value === selectedLanguage)?.label}主程序代码...`"
                ></textarea>
                <p class="text-sm text-gray-500 mt-2">主程序代码用于运行和测试，通常包含main函数或测试逻辑</p>
              </div>
            </div>
          </div>

          <!-- 测试样例文件 -->
          <div class="bg-gradient-to-r from-rose-50 to-pink-50 p-6 rounded-2xl border border-rose-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-rose-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path>
              </svg>
              测试样例文件
            </h3>
            <p class="text-sm text-gray-600 mb-6">上传测试用例文件，支持.txt格式。每个文件包含输入和输出数据，用"===="来分隔每个测试用例，用"==="来分隔输入和输出</p>
            
            <!-- 文件上传区域 -->
            <div
              class="border-2 border-dashed border-rose-300 rounded-xl p-8 text-center hover:border-rose-400 transition-all duration-200 bg-white/60 backdrop-blur-sm hover:bg-white/80"
              @dragover.prevent
              @drop.prevent="handleFileDrop"
            >
              <input
                ref="fileInput"
                type="file"
                multiple
                accept=".txt"
                class="hidden"
                @change="handleFileSelect"
              />
              
              <div v-if="testFiles.length === 0">
                <svg class="mx-auto h-16 w-16 text-rose-400" stroke="currentColor" fill="none" viewBox="0 0 48 48">
                  <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                </svg>
                <div class="mt-6">
                  <div class="flex flex-col sm:flex-row gap-3 justify-center">
                    <button
                      type="button"
                      class="px-6 py-3 bg-gradient-to-r from-rose-500 to-pink-500 text-white rounded-xl hover:from-rose-600 hover:to-pink-600 transition-all duration-200 transform hover:scale-105 shadow-lg hover:shadow-xl font-medium"
                      @click="() => ($refs.fileInput as HTMLInputElement)?.click()"
                    >
                      <svg class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path>
                      </svg>
                      上传文件
                    </button>
                    <button
                      type="button"
                      class="px-6 py-3 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl hover:from-blue-600 hover:to-indigo-600 transition-all duration-200 transform hover:scale-105 shadow-lg hover:shadow-xl font-medium"
                      @click="openTestCaseManager"
                    >
                      <svg class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                      </svg>
                      手动输入
                    </button>
                  </div>
                  <p class="text-gray-600 mt-3">或拖拽文件到此处</p>
                </div>
                <p class="text-sm text-gray-500 mt-4">支持 .txt 格式文件上传，或手动输入测试用例</p>
              </div>

              <!-- 已上传的文件列表 -->
              <div v-else class="space-y-2">
                <div
                  v-for="(file, index) in testFiles"
                  :key="index"
                  class="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
                >
                  <div class="flex items-center space-x-3">
                    <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    <div>
                      <p class="text-sm font-medium text-gray-900">{{ file.name }}</p>
                      <p class="text-xs text-gray-500">{{ formatFileSize(file.size) }}</p>
                    </div>
                  </div>
                  <button
                    type="button"
                    class="text-red-600 hover:text-red-800"
                    @click="removeTestFile(index)"
                  >
                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                  </button>
                </div>
                
                <div class="mt-4 flex flex-wrap gap-3">
                  <button
                    type="button"
                    class="text-blue-600 hover:text-blue-500 font-medium"
                    @click="() => ($refs.fileInput as HTMLInputElement)?.click()"
                  >
                    添加更多文件
                  </button>
                  <button
                    type="button"
                    class="px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-lg hover:from-green-600 hover:to-emerald-600 transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg font-medium"
                    @click="parseTestFiles"
                    :disabled="isParsingFiles"
                  >
                    <svg v-if="isParsingFiles" class="w-4 h-4 inline mr-2 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                    </svg>
                    <svg v-else class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    {{ isParsingFiles ? '解析中...' : '解析测试文件' }}
                  </button>
                  <button
                    type="button"
                    class="px-4 py-2 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-lg hover:from-blue-600 hover:to-indigo-600 transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg font-medium"
                    @click="openTestCaseManager"
                  >
                    <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                    </svg>
                    手动输入测试用例
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 测试用例管理器 -->
          <div v-if="showTestCaseManager" class="bg-gradient-to-r from-emerald-50 to-teal-50 p-6 rounded-2xl border border-emerald-200/50">
            <div class="flex items-center justify-between mb-6">
              <h3 class="text-lg font-semibold text-gray-900 flex items-center">
                <svg class="w-5 h-5 mr-2 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                </svg>
                测试用例管理 ({{ parsedTestCases.length }} 个)
              </h3>
              <div class="flex space-x-2">
                <button
                  type="button"
                  class="px-4 py-2 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-lg hover:from-blue-600 hover:to-blue-700 transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg font-medium"
                  @click="addTestCase"
                >
                  <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                  </svg>
                  添加测试用例
                </button>
                <button
                  type="button"
                  class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-all duration-200 font-medium"
                  @click="closeTestCaseManager"
                >
                  关闭
                </button>
              </div>
            </div>

            <!-- 测试用例列表 -->
            <div class="space-y-4 max-h-96 overflow-y-auto">
              <div
                v-for="(testCase, index) in parsedTestCases"
                :key="index"
                class="bg-white/80 backdrop-blur-sm rounded-xl border border-gray-200/50 p-4 shadow-sm hover:shadow-md transition-all duration-200"
              >
                <div class="flex items-center justify-between mb-3">
                  <div class="flex items-center space-x-3">
                    <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs font-semibold rounded-full">
                      测试用例 #{{ index + 1 }}
                    </span>
                    <label class="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        v-model="testCase.is_sample"
                        class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span class="text-sm text-gray-600">样例测试用例</span>
                    </label>
                  </div>
                  <button
                    type="button"
                    class="text-red-600 hover:text-red-800 transition-colors"
                    @click="removeTestCase(index)"
                  >
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                    </svg>
                  </button>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                      输入数据
                    </label>
                    <textarea
                      v-model="testCase.input"
                      rows="4"
                      class="w-full px-3 py-2 border border-gray-200/50 rounded-lg bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 transition-all duration-200 shadow-sm hover:shadow-md font-mono text-sm"
                      placeholder="输入数据..."
                    ></textarea>
                  </div>

                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                      预期输出
                    </label>
                    <textarea
                      v-model="testCase.expected_output"
                      rows="4"
                      class="w-full px-3 py-2 border border-gray-200/50 rounded-lg bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 transition-all duration-200 shadow-sm hover:shadow-md font-mono text-sm"
                      placeholder="预期输出..."
                    ></textarea>
                  </div>
                </div>
              </div>

              <!-- 空状态 -->
              <div v-if="parsedTestCases.length === 0" class="text-center py-8">
                <svg class="mx-auto h-16 w-16 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 48 48">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                </svg>
                <h3 class="mt-2 text-sm font-medium text-gray-900">暂无测试用例</h3>
                <p class="mt-1 text-sm text-gray-500">点击"添加测试用例"按钮来创建新的测试用例</p>
              </div>
            </div>
          </div>

          <!-- 标签选择 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              题目标签
            </label>
            <div class="space-y-3">
              <!-- 搜索标签 -->
              <div class="relative">
                <input
                  v-model="tagSearchQuery"
                  type="text"
                  placeholder="搜索标签..."
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  @input="filterTags"
                />
                <svg class="absolute right-3 top-2.5 h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                </svg>
              </div>

              <!-- 已选择的标签 -->
              <div v-if="selectedTags.length > 0" class="flex flex-wrap gap-2">
                <span class="text-sm text-gray-600">已选择：</span>
                <span
                  v-for="tag in selectedTags"
                  :key="tag.id"
                  class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium"
                  :style="{ backgroundColor: tag.color + '20', color: tag.color }"
                >
                  {{ tag.display_name }}
                  <button
                    type="button"
                    @click="removeTag(tag)"
                    class="ml-2 text-gray-500 hover:text-gray-700"
                  >
                    ×
                  </button>
                </span>
              </div>

              <!-- 可选标签列表 -->
              <div class="max-h-40 overflow-y-auto border border-gray-200 rounded-lg">
                <div
                  v-for="tag in filteredTags"
                  :key="tag.id"
                  class="flex items-center justify-between px-3 py-2 hover:bg-gray-50 cursor-pointer"
                  @click="toggleTag(tag)"
                >
                  <div class="flex items-center space-x-2">
                    <div
                      class="w-3 h-3 rounded-full"
                      :style="{ backgroundColor: tag.color }"
                    ></div>
                    <span class="text-sm font-medium">{{ tag.display_name }}</span>
                    <span class="text-xs text-gray-500">({{ tag.name }})</span>
                  </div>
                  <input
                    type="checkbox"
                    :checked="isTagSelected(tag)"
                    class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    @click.stop
                    @change="toggleTag(tag)"
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-end space-x-4 pt-8 border-t border-gray-200/50">
            <button
              type="button"
              class="px-8 py-3 border border-gray-300 rounded-xl text-gray-700 hover:bg-gray-50 transition-all duration-200 shadow-sm hover:shadow-md"
              @click="goBack"
            >
              取消
            </button>
            <button
              type="submit"
              :disabled="isSubmitting"
              class="px-8 py-3 bg-gradient-to-r from-emerald-600 to-teal-600 text-white rounded-xl hover:from-emerald-700 hover:to-teal-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 transform hover:scale-105 shadow-lg hover:shadow-xl"
            >
              <svg v-if="isSubmitting" class="w-5 h-5 inline mr-2 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
              </svg>
              <svg v-else class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
              </svg>
              {{ isSubmitting ? '创建中...' : '创建题目' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { questionApi } from '@/api/question'
import { testCaseApi, type TestCase } from '@/api/testcase'
import { useGlobalStore } from '@/stores/global'
import type { Tag, ProgrammingLanguage } from '@/types'

const router = useRouter()
const globalStore = useGlobalStore()

// 表单数据
const form = reactive({
  title: '',
  content: '',
  inputFormat: '',
  outputFormat: '',
  constraints: '',
  sampleInput: '',
  sampleOutput: '',
  difficulty: '',
  timeLimit: 1000,
  memoryLimit: 256,
  source: '',
  tagIds: [] as number[],
  basecode: {} as Record<string, string>,
  runCode: {} as Record<string, string>
})

// 编程语言相关
const programmingLanguages = [
  { value: 'cpp', label: 'C++' },
  { value: 'java', label: 'Java' },
  { value: 'python', label: 'Python' },
  { value: 'python3', label: 'Python 3' },
  { value: 'javascript', label: 'JavaScript' },
  { value: 'go', label: 'Go' },
  { value: 'rust', label: 'Rust' },
  { value: 'c', label: 'C' }
]

const selectedLanguage = ref<ProgrammingLanguage | null>(null)
const basecodeTemplates = reactive<Record<string, string>>({})
const runCodeTemplates = reactive<Record<string, string>>({})

// 测试文件相关
const testFiles = ref<File[]>([])

// 测试样例相关
const parsedTestCases = ref<TestCase[]>([])
const isParsingFiles = ref(false)
const showTestCaseManager = ref(false)

// 标签相关
const allTags = ref<Tag[]>([])
const filteredTags = ref<Tag[]>([])
const selectedTags = ref<Tag[]>([])
const tagSearchQuery = ref('')

// 状态
const isSubmitting = ref(false)

// 初始化表单默认值
onMounted(async () => {
  await loadTags()
  // 初始化代码模板
  programmingLanguages.forEach(lang => {
    basecodeTemplates[lang.value] = ''
    runCodeTemplates[lang.value] = ''
  })
  // 默认选择第一个语言
  if (programmingLanguages.length > 0) {
    selectedLanguage.value = programmingLanguages[0].value as ProgrammingLanguage
  }
})

// 加载标签列表
const loadTags = async () => {
  try {
    const response = await questionApi.getTags()
    if (response.code === 200 && response.data) {
      allTags.value = response.data
      filteredTags.value = response.data
    }
  } catch (error) {
    console.error('加载标签失败:', error)
    globalStore.addToast({
      type: 'error',
      title: '加载标签失败',
      message: '请刷新页面重试'
    })
  }
}

// 过滤标签
const filterTags = () => {
  if (!tagSearchQuery.value.trim()) {
    filteredTags.value = allTags.value
  } else {
    const query = tagSearchQuery.value.toLowerCase()
    filteredTags.value = allTags.value.filter(tag =>
      tag.name.toLowerCase().includes(query) ||
      tag.display_name.toLowerCase().includes(query)
    )
  }
}

// 切换标签选择状态
const toggleTag = (tag: Tag) => {
  const index = selectedTags.value.findIndex(t => t.id === tag.id)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tag)
  }
  updateFormTagIds()
}

// 移除标签
const removeTag = (tag: Tag) => {
  const index = selectedTags.value.findIndex(t => t.id === tag.id)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
    updateFormTagIds()
  }
}

// 检查标签是否已选择
const isTagSelected = (tag: Tag) => {
  return selectedTags.value.some(t => t.id === tag.id)
}

// 更新表单中的标签ID数组
const updateFormTagIds = () => {
  form.tagIds = selectedTags.value.map(tag => tag.id)
}

// 表单验证
const validateForm = () => {
  if (!form.title.trim()) {
    globalStore.addToast({
      type: 'error',
      title: '验证失败',
      message: '请输入题目标题'
    })
    return false
  }

  if (!form.content.trim()) {
    globalStore.addToast({
      type: 'error',
      title: '验证失败',
      message: '请输入题目描述'
    })
    return false
  }

  if (!form.difficulty) {
    globalStore.addToast({
      type: 'error',
      title: '验证失败',
      message: '请选择题目难度'
    })
    return false
  }

  // 验证测试用例
  if (parsedTestCases.value.length === 0) {
    globalStore.addToast({
      type: 'warning',
      title: '提示',
      message: '建议添加测试用例以确保题目质量'
    })
  }

  // 验证测试用例内容
  for (let i = 0; i < parsedTestCases.value.length; i++) {
    const testCase = parsedTestCases.value[i]
    if (!testCase.input.trim() || !testCase.expected_output.trim()) {
      globalStore.addToast({
        type: 'error',
        title: '验证失败',
        message: `测试用例 #${i + 1} 的输入或输出不能为空`
      })
      return false
    }
  }

  return true
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  isSubmitting.value = true

  try {
    // 准备代码模板数据
    const basecode: Record<string, string> = {}
    const runCode: Record<string, string> = {}
    
    // 只包含非空的代码模板
    Object.keys(basecodeTemplates).forEach(lang => {
      if (basecodeTemplates[lang].trim()) {
        basecode[lang] = basecodeTemplates[lang]
      }
    })
    
    Object.keys(runCodeTemplates).forEach(lang => {
      if (runCodeTemplates[lang].trim()) {
        runCode[lang] = runCodeTemplates[lang]
      }
    })

    const response = await questionApi.createQuestion({
      title: form.title,
      content: form.content,
      input_format: form.inputFormat || undefined,
      output_format: form.outputFormat || undefined,
      constraints: form.constraints || undefined,
      sample_input: form.sampleInput || undefined,
      sample_output: form.sampleOutput || undefined,
      difficulty: form.difficulty as 'Easy' | 'Medium' | 'Hard',
      time_limit: form.timeLimit,
      memory_limit: form.memoryLimit,
      source: form.source || undefined,
      tag_ids: form.tagIds,
      basecode: Object.keys(basecode).length > 0 ? basecode : undefined,
      run_code: Object.keys(runCode).length > 0 ? runCode : undefined
    })

    if (response.code === 200) {
      const questionId = response.data?.id
      
      // 如果有测试用例，创建测试用例
      if (parsedTestCases.value.length > 0 && questionId) {
        try {
          await testCaseApi.createTestCases(questionId, parsedTestCases.value)
          globalStore.addToast({
            type: 'success',
            title: '创建成功',
            message: `题目创建成功！已添加 ${parsedTestCases.value.length} 个测试用例`
          })
        } catch (testCaseError) {
          console.error('创建测试用例失败:', testCaseError)
          globalStore.addToast({
            type: 'warning',
            title: '部分成功',
            message: '题目创建成功，但测试用例创建失败'
          })
        }
      } else {
        globalStore.addToast({
          type: 'success',
          title: '创建成功',
          message: '题目创建成功！'
        })
      }
      
      // 跳转到题目管理页面
      router.push('/admin/questions')
    } else {
      globalStore.addToast({
        type: 'error',
        title: '创建失败',
        message: response.message || '创建题目失败，请重试'
      })
    }
  } catch (error) {
    console.error('创建题目失败:', error)
    globalStore.addToast({
      type: 'error',
      title: '创建失败',
      message: '网络错误，请检查网络连接后重试'
    })
  } finally {
    isSubmitting.value = false
  }
}

// 选择编程语言
const selectLanguage = (language: ProgrammingLanguage) => {
  selectedLanguage.value = language
}

// 文件上传相关方法
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files && target.files.length > 0) {
    const files = Array.from(target.files)
    addTestFiles(files)
  }
  // 重置input的value，确保下次选择文件时change事件能正常触发
  target.value = ''
}

const handleFileDrop = (event: DragEvent) => {
  if (event.dataTransfer?.files) {
    const files = Array.from(event.dataTransfer.files)
    addTestFiles(files)
  }
}

const addTestFiles = (files: File[]) => {
  const validFiles = files.filter(file => {
    // 检查文件类型
    if (!file.name.toLowerCase().endsWith('.txt')) {
      globalStore.addToast({
        type: 'warning',
        title: '文件格式错误',
        message: `文件 ${file.name} 不是 .txt 格式，已跳过`
      })
      return false
    }
    
    // 检查文件大小 (限制为1MB)
    if (file.size > 1024 * 1024) {
      globalStore.addToast({
        type: 'warning',
        title: '文件过大',
        message: `文件 ${file.name} 超过1MB限制，已跳过`
      })
      return false
    }
    
    return true
  })
  
  testFiles.value.push(...validFiles)
  
  if (validFiles.length > 0) {
    globalStore.addToast({
      type: 'success',
      title: '文件上传成功',
      message: `成功添加 ${validFiles.length} 个测试文件`
    })
  }
}

const removeTestFile = (index: number) => {
  testFiles.value.splice(index, 1)
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 解析测试文件
const parseTestFiles = async () => {
  if (testFiles.value.length === 0) {
    globalStore.addToast({
      type: 'warning',
      title: '没有文件',
      message: '请先上传测试文件'
    })
    return
  }

  isParsingFiles.value = true
  
  try {
    const response = await testCaseApi.parseTestFiles(testFiles.value)
    
    if (response.code === 200 && response.data) {
      parsedTestCases.value = response.data.test_cases || []
      
      if (response.data.errors && response.data.errors.length > 0) {
        globalStore.addToast({
          type: 'warning',
          title: '解析完成',
          message: `成功解析 ${parsedTestCases.value.length} 个测试用例，但有 ${response.data.errors.length} 个错误`
        })
        // 显示错误信息
        console.warn('解析错误:', response.data.errors)
      } else {
        globalStore.addToast({
          type: 'success',
          title: '解析成功',
          message: `成功解析 ${parsedTestCases.value.length} 个测试用例`
        })
      }
      
      // 显示测试用例管理器
      showTestCaseManager.value = true
    } else {
      globalStore.addToast({
        type: 'error',
        title: '解析失败',
        message: response.message || '解析测试文件失败'
      })
    }
  } catch (error) {
    console.error('解析测试文件失败:', error)
    globalStore.addToast({
      type: 'error',
      title: '解析失败',
      message: '网络错误，请检查网络连接后重试'
    })
  } finally {
    isParsingFiles.value = false
  }
}

// 编辑测试用例
const editTestCase = (index: number) => {
  // 这里可以实现编辑测试用例的逻辑
  console.log('编辑测试用例:', index)
}

// 删除测试用例
const removeTestCase = (index: number) => {
  parsedTestCases.value.splice(index, 1)
  globalStore.addToast({
    type: 'success',
    title: '删除成功',
    message: '测试用例已删除'
  })
}

// 添加新的测试用例
const addTestCase = () => {
  parsedTestCases.value.push({
    input: '',
    expected_output: '',
    is_sample: false
  })
}

// 打开测试用例管理器
const openTestCaseManager = () => {
  showTestCaseManager.value = true
}

// 关闭测试用例管理器
const closeTestCaseManager = () => {
  showTestCaseManager.value = false
}

// 返回上一页
const goBack = () => {
  router.back()
}
</script>
